const Websocket = require('ws')
const path = require('path')
const fileRead = require('../utils/file_utils')
module.exports.wsUtil = () => {
  const wss = new Websocket.Server({
    port: 9998
  })
  wss.on('connection', client => {
    console.log(' 客户端连接...');
    client.on('message', async (msg) => {
      const payload = JSON.parse(msg)
      console.log(payload);
      if (payload.action === 'getData') {
        let filePath = `../data/${payload.chartName}.json`
        console.log(filePath);
        filePath = path.join(__dirname, filePath)
        console.log(filePath);
        const res = await fileRead(filePath)
        payload.data = res
        client.send(JSON.stringify(payload))
      } else {
        // wss.clients // 所有客户端的连接
        wss.clients.forEach(client => {
          client.send(JSON.stringify(payload))
        })
      }

    })
  })
}